package com.youdoneed.community.shortVideo.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.youdoneed.base.application.AppException;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.shortVideo.dao.MusiclibraryMapper;
import com.youdoneed.community.shortVideo.dao.MusicrecommendMapper;
import com.youdoneed.community.shortVideo.dao.MusictypeMapper;
import com.youdoneed.community.shortVideo.dao.MusictyperelMapper;
import com.youdoneed.community.shortVideo.entity.Musiclibrary;
import com.youdoneed.community.shortVideo.entity.Musicrecommend;
import com.youdoneed.community.shortVideo.entity.Musictyperel;
import com.youdoneed.community.shortVideo.vo.RecommendVo;

@Service
public class MusicrecommendService {

    private final Logger logger = LoggerFactory.getLogger(MusicrecommendService.class);

    private final String musicLibraryType = "2aeded1129784decbab8b8bf18329c7c";

    @Autowired
    MusicrecommendMapper musicrecommendMapper;

    @Autowired
    MusictypeMapper musictypeMapper;

    @Autowired
    MusiclibraryMapper musiclibraryMapper;

    @Autowired
    MusictyperelMapper musictyperelMapper;

    /**
     * 向音乐分类中添加推荐音乐
     *
     * @param musictyperel
     * @author lixs
     * @Date 2017.9.4
     */
    @Transactional
    public Boolean addRecommendMusicToTypeBatch(List<String> musicTypeRelId) {
        if (null == musicTypeRelId) {
            throw new AppException("音乐对象不能为空");
        }

        for (String musictypeRelId : musicTypeRelId) {
            Musictyperel musictyperel = musictyperelMapper.selectByPrimaryKey(musictypeRelId);
            if (null == musictyperel) {
                continue;
            }
//			logger.info("我已经走到这一步了"+typeId);
            Musicrecommend musicrecommend = musicrecommendMapper.findTheUnique(musictyperel.getMusicId(), musictyperel.getTypeId());
            if (null != musicrecommend) {
                logger.info("推荐列表中已有这首歌");
                continue;
            }
            //通过类型id查看推荐音乐的数量。
            int total = musicrecommendMapper.countByTypeId(musictyperel.getTypeId());
            Musicrecommend musicrecommendnew = new Musicrecommend();
            musicrecommendnew.setMusicId(musictyperel.getMusicId());
            musicrecommendnew.setPlayCount(musictyperel.getPlayCount());
            musicrecommendnew.setRecommendMusicTypeId(StringUUIdUtil.getUUID());
            musicrecommendnew.setSort(total + 1);
            musicrecommendnew.setTypeId(musictyperel.getTypeId());
            musicrecommendnew.setCreateDate(new Date());
            musicrecommendMapper.insertSelective(musicrecommendnew);
        }
        return true;
    }

    /**
     * 查询分类下的推荐音乐
     *
     * @param typeId
     * @author lixs
     * @Date 2017.9.4
     */
    public List<RecommendVo> findRecommendMusic(String typeId, Integer currentPage, Integer rows) {
        if (!StringUtils.hasText(typeId)) {
            throw new AppException("类型id不能为空");
        }
        PageHelper.startPage(currentPage, rows);
        List<RecommendVo> musiclibrary = musicrecommendMapper.findRecommendMusic(typeId);
        if (null == musiclibrary) {
            throw new AppException("该音乐分类下没有任何音乐");
        }
        return musiclibrary;
    }

    /**
     * 批量移除推荐列表中的音乐
     *
     * @param musicrecommend
     * @author lixs
     * @Date 2017.9.4
     */

    @Transactional
    public Boolean removeRecommendMusic(List<String> recommendMusicTypeId, String typeId) {
        if (null == recommendMusicTypeId) {
            throw new AppException("未选中任何推荐的音乐");
        }
        //移除推荐列表中的部分音乐
        for (int index = 0; index < recommendMusicTypeId.size(); index++) {
            musicrecommendMapper.deleteByPrimaryKey(recommendMusicTypeId.get(index));
        }
        logger.info("参数id" + recommendMusicTypeId.size());
        List<Musicrecommend> musicRecommend = musicrecommendMapper.findRecommendMusicByTypeId(typeId);
        if (null == musicRecommend) {
            return true;
        }
        logger.info("musicRecommend.size()" + musicRecommend.size());
        //删除分类下的部分推荐音乐后，对剩下的音乐进行重新排序
        for (int index = 0; index < musicRecommend.size(); index++) {
            musicRecommend.get(index).setSort(index + 1);
            musicrecommendMapper.updateByPrimaryKeySelective(musicRecommend.get(index));
        }
        return true;
    }

    /**
     * 查询分类下是否存在某一推荐音乐
     *
     * @param musicId
     * @param typeId
     * @author lixs
     * @Date 2017.9.20
     */
    public Boolean recommendUnique(String musicId, String typeId) {
        Musicrecommend musicrecommend = musicrecommendMapper.findTheUnique(musicId, typeId);
        if (null != musicrecommend) {
            throw new AppException("推荐列表中已有这首歌");
        }
        logger.info(musicrecommend.getMusicId() + "推荐音乐id");
        return true;
    }

    /**
     * 通过歌手或者歌曲名查询推荐歌曲
     *
     * @param name
     * @author lixs
     * @Date 2017.9.20
     */
    public List<Musiclibrary> findRecommendMusicByName(String name, Integer currentPage, Integer total) {

        PageHelper.startPage(currentPage, total);
        List<Musiclibrary> musiclibrary = musicrecommendMapper.findRecommendMusicByName(name);
        if (null == musiclibrary) {
            throw new AppException("未找到推荐音乐列表");
        }
        return musiclibrary;
    }

    public int findRecommendMusicByNameForTotal(String name) {
        return musicrecommendMapper.findRecommendMusicByNameForTotal(name);
    }

    /**
     * 交换两个推荐音乐的顺序(箭头向上)
     *
     * @param musicrecommendId
     * @author lixs
     * @Date 2017.9.27
     */
    @Transactional
    public int exchangeSortTop(String musicrecommendId) {
        if (!StringUtils.hasText(musicrecommendId)) {
            throw new AppException("推荐音乐id不能为空");
        }
        Musicrecommend musicrecommendtop = musicrecommendMapper.selectByPrimaryKey(musicrecommendId);
        if (null == musicrecommendtop) {
            throw new AppException("不存在该推荐音乐");
        }
        Musicrecommend MusicrecommendBehind = musicrecommendMapper.findRecommendMusicBySort(musicrecommendtop.getSort() - 1, musicrecommendtop.getTypeId());
        if (null == MusicrecommendBehind) {
            throw new AppException("不存在该推荐音乐");
        }
        int sort = musicrecommendtop.getSort();
        logger.info("第一个排序是" + sort);
        musicrecommendtop.setSort(MusicrecommendBehind.getSort());
        musicrecommendMapper.updateByPrimaryKeySelective(musicrecommendtop);
        MusicrecommendBehind.setSort(sort);
        return musicrecommendMapper.updateByPrimaryKeySelective(MusicrecommendBehind);
    }

    /**
     * 交换两个推荐音乐的顺序(箭头向下)
     *
     * @param musicrecommendId
     * @author lixs
     * @Date 2017.10.20
     */
    @Transactional
    public int exchangeSortBehind(String musicrecommendId) {
        if (!StringUtils.hasText(musicrecommendId)) {
            throw new AppException("推荐音乐id不能为空");
        }
        Musicrecommend musicrecommendBehind = musicrecommendMapper.selectByPrimaryKey(musicrecommendId);
        if (null == musicrecommendBehind) {
            throw new AppException("不存在该推荐音乐");
        }
        Musicrecommend MusicrecommendTop = musicrecommendMapper.findRecommendMusicBySort(musicrecommendBehind.getSort() + 1, musicrecommendBehind.getTypeId());
        if (null == MusicrecommendTop) {
            throw new AppException("不存在该推荐音乐");
        }
        int sort = musicrecommendBehind.getSort();
        logger.info("第一个排序是" + sort);
        musicrecommendBehind.setSort(MusicrecommendTop.getSort());
        musicrecommendMapper.updateByPrimaryKeySelective(musicrecommendBehind);
        MusicrecommendTop.setSort(sort);
        return musicrecommendMapper.updateByPrimaryKeySelective(MusicrecommendTop);
    }

    /**
     * 置顶推荐的音乐
     *
     * @param musicrecommendId
     */
    public void top(String musicrecommendId) {
        if (!StringUtils.hasText(musicrecommendId)) {
            throw new AppException("推荐音乐id不能为空");
        }
        Musicrecommend musicrecommend = musicrecommendMapper.selectByPrimaryKey(musicrecommendId);
        if (null == musicrecommend) {
            throw new AppException("不存在该推荐音乐");
        }
        logger.info("musicrecommendId："+musicrecommendId);

        //找到第一个推荐的音乐
        Musicrecommend firstMusic = musicrecommendMapper.getFirstMusicRecommand(musicrecommend.getTypeId());
        if (firstMusic.getRecommendMusicTypeId().equals(musicrecommendId)) {
            logger.info("firstMusic.getMusicId()："+firstMusic.getRecommendMusicTypeId());
            logger.info("equal");
            return;
        }
        logger.info("firstMusic.getSort():"+firstMusic.getSort());

        musicrecommendMapper.updateSort(musicrecommendId, firstMusic.getSort() - 1);

    }

    /**
     * 音乐播放后播放次数更新
     *
     * @param recommendMusicTypeId
     * @author lixs
     * @Date 2017.9.28
     */
    @Transactional
    public int updatePlayCount(String musicId) {
        if (!StringUtils.hasText(musicId)) {
            throw new AppException("音乐id不能为空");
        }

        //音乐库中的该音乐播放次数加1
        Musiclibrary musiclibrary = musiclibraryMapper.selectByPrimaryKey(musicId);
        if (null == musiclibrary) {
            throw new AppException("该音乐不存在");
        }
        musiclibrary.setPlayCount(musiclibrary.getPlayCount() + 1);


        //音乐分类下的该音乐播放次数也要加1
        List<Musictyperel> musictyperel = musictyperelMapper.findMusictyperelByMusicId(musicId);
        if (null == musictyperel) {
            throw new AppException("分类下的音乐为空");
        }
        for (Musictyperel musictyperelNew : musictyperel) {
            musictyperelNew.setPlayCount(musictyperelNew.getPlayCount() + 1);
            musictyperelMapper.updateByPrimaryKeySelective(musictyperelNew);
        }

        List<Musicrecommend> musicrecommend = musicrecommendMapper.findMusicById(musicId);
        if (null == musicrecommend) {
            throw new AppException("推荐音乐对象不能为空");
        }
        //推荐音乐播放次数加1
        for (Musicrecommend musicrecommendNew : musicrecommend) {
            musicrecommendNew.setPlayCount(musicrecommendNew.getPlayCount() + 1);
            musicrecommendMapper.updateByPrimaryKeySelective(musicrecommendNew);
        }

        return musiclibraryMapper.updateByPrimaryKeySelective(musiclibrary);


    }

    /**
     * 从音乐库添加音乐到首页的推荐音乐
     *
     * @param musiclibrary
     * @author lixs
     * @Date 2017.10.11
     */
    @Transactional
    public Boolean addMusicLibraryRecommend(List<String> musicId) {

        if (null == musicId) {
            throw new AppException("您未选中任何音乐");
        }
        //查询主页分类下的推荐音乐。
        int total = musicrecommendMapper.countMusicLibraryRecommend();
        for (int index = 0; index < musicId.size(); index++) {

            Musicrecommend musicrecommendNew = musicrecommendMapper.findTheUnique(musicId.get(index), musicLibraryType);
            if (null != musicrecommendNew) {
                logger.info("这首歌已经在推荐列表中");
                continue;
            }
            Musicrecommend musicrecommend = new Musicrecommend();
            musicrecommend.setRecommendMusicTypeId(StringUUIdUtil.getUUID());
            musicrecommend.setCreateDate(new Date());
            musicrecommend.setMusicId(musicId.get(index));
            musicrecommend.setPlayCount(0);
            musicrecommend.setTypeId(musicLibraryType);
            musicrecommend.setSort(total + index + 1);
            musicrecommendMapper.insertSelective(musicrecommend);
        }
        return true;
    }

    /**
     * 查询分类下的推荐音乐
     *
     * @param typeId
     * @author lixs
     * @Date 2017.9.4
     */
    public List<RecommendVo> findLibraryRecommendMusic(Integer currentPage, Integer rows) {
        PageHelper.startPage(currentPage, rows);
        List<RecommendVo> musiclibrary = musicrecommendMapper.findMusiclibraryRecommendMusic();
        if (null == musiclibrary) {
            throw new AppException("该音乐分类下没有任何音乐");
        }
        return musiclibrary;
    }

    /**
     * 批量移除推荐列表中的音乐
     *
     * @param musicrecommend
     * @author lixs
     * @Date 2017.9.4
     */
    @Transactional
    public Boolean removeLibraryRecommendMusic(List<String> recommendMusicTypeId) {
        if (null == recommendMusicTypeId) {
            throw new AppException("未选中任何推荐的音乐");
        }
        for (int index = 0; index < recommendMusicTypeId.size(); index++) {
            musicrecommendMapper.deleteByPrimaryKey(recommendMusicTypeId.get(index));
        }
        logger.info("参数id" + recommendMusicTypeId.size());

        List<Musicrecommend> musicRecommend = musicrecommendMapper.findLibraryRecommendMusic();
        if (null == musicRecommend) {
            throw new AppException("首页音乐分类下没有任何推荐音乐");
        }
        logger.info("musicRecommend.size()" + musicRecommend.size());
        for (int index = 0; index < musicRecommend.size(); index++) {
            musicRecommend.get(index).setSort(index + 1);
            musicrecommendMapper.updateByPrimaryKeySelective(musicRecommend.get(index));
        }
        return true;
    }

    public int findRecommendMusicForTotal(String typeId) {
        if (!StringUtils.hasText(typeId)) {
            throw new AppException("类型id不能为空");
        }
        return musicrecommendMapper.countByTypeId(typeId);
    }

    public int findMusiclibraryRecommendMusicForTotal() {
        return musicrecommendMapper.findMusiclibraryRecommendMusicForTotal();
    }

    /**
     * 随机抽取一首推荐音乐
     *
     * @author lixs
     * @Date 2017.10.23
     */
    public RecommendVo findRandomMusic() {
        List<RecommendVo> musicrecommend = musicrecommendMapper.findAllRecommend();
        int index = (int) (Math.random() * (musicrecommend.size() - 1) + 1);
        if (index < musicrecommend.size()) {
            return musicrecommend.get(index);
        }
        return musicrecommend.get(0);
    }


    /**
     * 通过名字查询推荐音乐(后台页面)
     *
     * @param typeId
     * @param name
     * @param currentPage
     * @param total
     * @return
     */
    public List<RecommendVo> findRecommendMusicByNameAndTypeId(String typeId, String name, Integer currentPage, Integer total) {

        PageHelper.startPage(currentPage, total);
        return musicrecommendMapper.findRecommendMusicByNameAndTypeId(typeId, name);

    }

    public int countRecommendMusicByNameAndTypeId(String typeId, String name) {
        return musicrecommendMapper.countRecommendMusicByNameAndTypeId(typeId, name);
    }

    /**
     * 将分类下的音乐全部推荐
     *
     * @param typeId
     * @author lixs
     * @Date 2017.11.15
     */
    @Transactional
    public Boolean addAllRecommendMusic(String typeId) {
        //获取分类下的全部音乐
        List<Musictyperel> musictyperels = musictyperelMapper.selectByTypeId(typeId);
        if (null == musictyperels) {
            throw new AppException("分类音乐对象不能为空");
        }
        for (Musictyperel musictyperel : musictyperels) {
            //去除重复音乐数据
            Musicrecommend musicrecommend = musicrecommendMapper.findTheUnique(musictyperel.getMusicId(), musictyperel.getTypeId());
            if (null != musicrecommend) {
                logger.info("推荐列表中已有这首歌");
                continue;
            }
            //获取音乐推荐列表中的音乐数
            int total = musicrecommendMapper.countByTypeId(typeId);

            Musicrecommend recommend = new Musicrecommend();
            recommend.setCreateDate(new Date());
            recommend.setMusicId(musictyperel.getMusicId());
            recommend.setPlayCount(0);
            recommend.setRecommendMusicTypeId(StringUUIdUtil.getUUID());
            recommend.setSort(total + 1);
            recommend.setTypeId(typeId);
            musicrecommendMapper.insertSelective(recommend);
        }
        return true;
    }
}
